package com.logos.musicframe.ui.javafx;

import com.logos.musicframe.controller.PlaylistController;
import com.logos.musicframe.controller.SongsController;
import com.logos.musicframe.controller.SongsLikedController;
import com.logos.musicframe.controller.SongsPlaylistController;
import com.logos.musicframe.controller.UsersController;
import com.logos.musicframe.req.SongsReq;
import com.logos.musicframe.resp.PlaylistResp;
import com.logos.musicframe.resp.SongsResp;
import com.logos.musicframe.resp.UsersResp;
import com.logos.musicframe.req.UsersReq;
import com.logos.musicframe.result.Result;
import com.logos.musicframe.service.UsersService;
import com.logos.musicframe.utils.AudioUtils;
import com.logos.musicframe.utils.JavaFxMusicPlayer;
import com.logos.musicframe.utils.SpringContextUtil;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.shape.Circle;
import javafx.stage.FileChooser;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author logos
 * date 2025/6/14 15:14
 * @version v1.0
 * @Package com.logos.musicframe.ui.javafx
 */
@Slf4j
public class PersonalCenterUi {
    
    private UsersController usersController = SpringContextUtil.getBean(UsersController.class);
    private SongsLikedController songsLikedController = SpringContextUtil.getBean(SongsLikedController.class);
    private SongsController songsController = SpringContextUtil.getBean(SongsController.class);
    private SongsPlaylistController songsPlaylistController = SpringContextUtil.getBean(SongsPlaylistController.class);
    private UsersService usersService = SpringContextUtil.getBean(UsersService.class);
    private JavaFxMusicPlayer player;
    
    // 当前选中的歌曲
    private SongsResp currentSong;

    private Button editProfileButton;
    
    // 内容容器的引用，用于刷新UI
    private VBox contentBox;
    
    // 当前选中的内容类型
    private String currentContentType = "liked"; // 默认显示喜欢的歌曲
    
    // 内容区域引用
    private VBox contentArea;
    
    // 回调接口，用于通知主UI更新当前歌曲
    private SongSelectedCallback songSelectedCallback;
    
    // 回调接口，用于通知主UI更新用户信息
    private UserInfoUpdatedCallback userInfoUpdatedCallback;
    
    // 主UI实例，用于调用添加到歌单对话框
    private MainMusicPlayerUi mainUI;
    
    public PersonalCenterUi(JavaFxMusicPlayer player, SongSelectedCallback songSelectedCallback) {
        this.player = player;
        this.songSelectedCallback = songSelectedCallback;
        
        // 获取主UI实例
        try {
            this.mainUI = SpringContextUtil.getBean(MainMusicPlayerUi.class);
        } catch (Exception e) {
            log.error("获取MainMusicPlayerUi实例失败", e);
        }
    }
    
    public PersonalCenterUi(JavaFxMusicPlayer player, SongSelectedCallback songSelectedCallback, UserInfoUpdatedCallback userInfoUpdatedCallback) {
        this.player = player;
        this.songSelectedCallback = songSelectedCallback;
        this.userInfoUpdatedCallback = userInfoUpdatedCallback;
        
        // 获取主UI实例
        try {
            this.mainUI = SpringContextUtil.getBean(MainMusicPlayerUi.class);
        } catch (Exception e) {
            log.error("获取MainMusicPlayerUi实例失败", e);
        }
    }
    
    public VBox createPersonalCenter() {
        // 创建一个内容容器，用于放置所有内容
        VBox contentBox = new VBox(20);
        contentBox.setPadding(new Insets(20));
        contentBox.setMinWidth(700);  // 设置最小宽度
        contentBox.setPrefWidth(800); // 设置首选宽度
        contentBox.setMaxWidth(900);  // 设置最大宽度
        
        // 保存内容容器的引用
        this.contentBox = contentBox;
        
        // 标题
        Label titleLabel = new Label("个人中心");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
        
        // 获取当前用户信息
        Result<UsersResp> currentUserInfo = usersController.getCurrentUserInfo();
        UsersResp currentUser = null;
        if (currentUserInfo.isSuccess()) {
            currentUser = currentUserInfo.getData();
        }
        
        // 用户信息卡片
        VBox userInfoCard = createUserInfoCard(currentUser);
        
        // 统计信息卡片
        HBox statsCards = createStatsCards();
        
        // 添加上传音乐按钮
        VBox uploadMusicBox = createUploadMusicBox();
        
        // 创建内容区域标题和内容区域
        Label contentTitleLabel = new Label(getCurrentContentTitle());
        contentTitleLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold; -fx-padding: 15 0 5 0;");
        
        // 创建内容区域
        contentArea = new VBox(5);
        updateContentArea();
        
        // 添加所有组件到内容容器
        contentBox.getChildren().addAll(titleLabel, userInfoCard, statsCards, uploadMusicBox, contentTitleLabel, contentArea);
        
        // 创建滚动面板，将内容容器放入其中
        ScrollPane scrollPane = new ScrollPane(contentBox);
        scrollPane.setFitToWidth(false); // 不自动适应宽度
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED); // 需要时显示水平滚动条
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
        scrollPane.getStyleClass().add("edge-to-edge");
        scrollPane.setStyle("-fx-background-color: transparent;");
        
        // 创建包含滚动面板的VBox
        VBox personalCenterPage = new VBox();
        personalCenterPage.getChildren().add(scrollPane);
        VBox.setVgrow(scrollPane, Priority.ALWAYS);
        
        return personalCenterPage;
    }
    
    /**
     * 获取当前内容区域的标题
     */
    private String getCurrentContentTitle() {
        switch (currentContentType) {
            case "liked":
                return "喜欢的歌曲";
            case "recent":
                return "最近播放";
            case "playlists":
                return "创建的歌单";
            default:
                return "喜欢的歌曲";
        }
    }
    
    /**
     * 更新内容区域
     */
    private void updateContentArea() {
        if (contentArea == null) {
            return;
        }
        
        // 清空当前内容
        contentArea.getChildren().clear();
        
        // 根据当前内容类型显示不同内容
        switch (currentContentType) {
            case "liked":
                contentArea.getChildren().add(createLikedSongsList());
                break;
            case "recent":
                contentArea.getChildren().add(createRecentPlaysList());
                break;
            case "playlists":
                contentArea.getChildren().add(createPlaylistsList());
                break;
            default:
                contentArea.getChildren().add(createLikedSongsList());
                break;
        }
    }
    
    /**
     * 切换内容类型
     */
    private void switchContentType(String contentType) {
        if (!contentType.equals(currentContentType)) {
            currentContentType = contentType;
            
            // 更新内容区域标题
            if (contentBox != null && contentBox.getChildren().size() > 5) {
                Label contentTitleLabel = (Label) contentBox.getChildren().get(4);
                contentTitleLabel.setText(getCurrentContentTitle());
            }
            
            // 更新内容区域
            updateContentArea();
        }
    }
    
    private VBox createUserInfoCard(UsersResp currentUser) {
        VBox userInfoCard = new VBox(15);
        userInfoCard.setPadding(new Insets(20));
        userInfoCard.setStyle("-fx-background-color: white; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 10, 0, 0, 0);");
        
        // 用户头像和基本信息
        HBox userBasicInfo = new HBox(20);
        userBasicInfo.setAlignment(Pos.CENTER_LEFT);
        
        // 头像
        ImageView avatarView = new ImageView();
        avatarView.setFitWidth(100);
        avatarView.setFitHeight(100);
        
        // 圆形裁剪
        Circle clip = new Circle(50, 50, 50);
        avatarView.setClip(clip);
        
        // 设置头像图片
        String avatarPath = "static/default-avatar.png";
        if (currentUser != null && currentUser.getAvatar() != null && !currentUser.getAvatar().isEmpty()) {
            avatarPath = currentUser.getAvatar();
        }
        avatarView.setImage(new Image(avatarPath));
        
        // 用户信息
        VBox userTextInfo = new VBox(10);
        
        // 用户名
        Label usernameLabel = new Label("用户名：" + (currentUser != null ? currentUser.getUsername() : "未知用户"));
        usernameLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
        
        // 手机号
        Label phoneLabel = new Label("手机号：" + (currentUser != null ? currentUser.getPhone() : "未绑定"));
        phoneLabel.setStyle("-fx-font-size: 14px;");
        
        // 计算用户加入天数
        String joinDaysText = "未知";
        if (currentUser != null && currentUser.getCreatedAt() != null) {
            Date createdAt = currentUser.getCreatedAt();
            Date now = new Date();
            long diffMills = Math.abs(now.getTime() - createdAt.getTime());
            long diffDays = diffMills / (24 * 60 * 60 * 1000);
            joinDaysText = diffDays + " 天";
        }
        
        // 显示加入天数
        Label joinDaysLabel = new Label("来到Logos音乐：" + joinDaysText);
        joinDaysLabel.setStyle("-fx-font-size: 14px;");
        
        // 个性签名
        Label signatureLabel = new Label("个性签名：" + (currentUser != null && currentUser.getSignature() != null ? 
                                         currentUser.getSignature() : "这个人很懒，什么都没留下"));
        signatureLabel.setStyle("-fx-font-size: 14px; -fx-font-style: italic;");
        
        userTextInfo.getChildren().addAll(usernameLabel, phoneLabel, joinDaysLabel, signatureLabel);
        userBasicInfo.getChildren().addAll(avatarView, userTextInfo);
        
        // 操作按钮区域
        HBox actionButtons = new HBox(15);
        actionButtons.setAlignment(Pos.CENTER_LEFT);
        
        editProfileButton = new Button("修改资料");
        editProfileButton.setStyle("-fx-background-color: #1db954; -fx-text-fill: white; -fx-font-weight: bold;");
        
        Button changePasswordButton = new Button("修改密码");
        changePasswordButton.setStyle("-fx-background-color: #f0f0f0; -fx-text-fill: #333;");
        
        Button bindPhoneButton = new Button("绑定手机");
        bindPhoneButton.setStyle("-fx-background-color: #f0f0f0; -fx-text-fill: #333;");
        
        actionButtons.getChildren().addAll(editProfileButton, changePasswordButton, bindPhoneButton);
        
        // 绑定按钮事件
        editProfileButton.setOnAction(e -> {
            // 显示编辑个人资料对话框
            showEditProfileDialog(currentUser);
        });
        
        changePasswordButton.setOnAction(e -> {
            // TODO: 实现修改密码功能
            log.info("点击了修改密码按钮");
        });
        
        bindPhoneButton.setOnAction(e -> {
            // 实现绑定手机功能
            log.info("点击了绑定手机按钮");
            showBindPhoneDialog(currentUser);
        });
        
        // 将所有内容添加到用户信息卡片
        userInfoCard.getChildren().addAll(userBasicInfo, actionButtons);
        
        return userInfoCard;
    }
    
    private HBox createStatsCards() {
        HBox statsCards = new HBox(15);
        statsCards.setAlignment(Pos.CENTER);
        
        // 获取喜欢的歌曲数量和列表
        AtomicInteger likedSongsCount = new AtomicInteger();
        List<SongsResp> likedSongs = new ArrayList<>();
        Result<List<SongsResp>> likedSongsResult = songsLikedController.getUserLikedSongs();
        if (likedSongsResult.isSuccess() && likedSongsResult.getData() != null) {
            likedSongs = likedSongsResult.getData();
            likedSongsCount.set(likedSongs.size());
        }
        
        // 喜欢的歌曲数
        VBox likedSongsCard = createStatsCard("喜欢的歌曲", String.valueOf(likedSongsCount.get()), "static/heart-icon.png");
        likedSongsCard.setCursor(javafx.scene.Cursor.HAND); // 设置鼠标指针为手型
        
        // 添加点击事件
        likedSongsCard.setOnMouseClicked(e -> {
            switchContentType("liked");
        });
        
        // 设置选中样式
        if ("liked".equals(currentContentType)) {
            likedSongsCard.setStyle(likedSongsCard.getStyle() + "-fx-border-color: #1db954; -fx-border-width: 0 0 3 0;");
        }
        
        // 获取最近播放数量 (假设有10首)
        int recentPlaysCount = 10; // 这里应该从后端获取实际数据
        
        // 最近播放数
        VBox recentPlaysCard = createStatsCard("最近播放", String.valueOf(recentPlaysCount), "static/history-play.png");
        recentPlaysCard.setCursor(javafx.scene.Cursor.HAND); // 设置鼠标指针为手型
        
        // 添加点击事件
        recentPlaysCard.setOnMouseClicked(e -> {
            switchContentType("recent");
        });
        
        // 设置选中样式
        if ("recent".equals(currentContentType)) {
            recentPlaysCard.setStyle(recentPlaysCard.getStyle() + "-fx-border-color: #1db954; -fx-border-width: 0 0 3 0;");
        }
        
        // 获取创建的歌单数
        int playlistsCount = 0;
        Result<List<PlaylistResp>> playlistResult = SpringContextUtil.getBean(PlaylistController.class).queryByUserId();
        if (playlistResult.isSuccess() && playlistResult.getData() != null) {
            playlistsCount = playlistResult.getData().size();
        }
        
        // 创建的歌单数
        VBox playlistsCard = createStatsCard("创建的歌单", String.valueOf(playlistsCount), "static/playlist-icon.png");
        playlistsCard.setCursor(javafx.scene.Cursor.HAND); // 设置鼠标指针为手型
        
        // 添加点击事件
        playlistsCard.setOnMouseClicked(e -> {
            switchContentType("playlists");
        });
        
        // 设置选中样式
        if ("playlists".equals(currentContentType)) {
            playlistsCard.setStyle(playlistsCard.getStyle() + "-fx-border-color: #1db954; -fx-border-width: 0 0 3 0;");
        }
        
        statsCards.getChildren().addAll(likedSongsCard, recentPlaysCard, playlistsCard);
        
        return statsCards;
    }
    
    private VBox createLikedSongsList() {
        VBox likedSongsList = new VBox(5);
        likedSongsList.setPadding(new Insets(10));
        likedSongsList.setStyle("-fx-background-color: white; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 0);");
        likedSongsList.setMinWidth(600); // 设置最小宽度
        likedSongsList.setPrefWidth(700); // 设置首选宽度
        likedSongsList.setMaxWidth(800); // 设置最大宽度
        
        // 获取喜欢的歌曲列表
        List<SongsResp> likedSongs = new ArrayList<>();
        Result<List<SongsResp>> likedSongsResult = songsLikedController.getUserLikedSongs();
        if (likedSongsResult.isSuccess() && likedSongsResult.getData() != null) {
            likedSongs = likedSongsResult.getData();
        }
        
        if (likedSongs.isEmpty()) {
            Label emptyLabel = new Label("暂无喜欢的歌曲");
            emptyLabel.setStyle("-fx-text-fill: #999; -fx-font-style: italic;");
            likedSongsList.getChildren().add(emptyLabel);
        } else {
            // 创建表头
            HBox headerRow = new HBox(10);
            headerRow.setPadding(new Insets(5, 5, 10, 5));
            headerRow.setAlignment(Pos.CENTER_LEFT);
            
            Label indexHeader = new Label("#");
            indexHeader.setStyle("-fx-font-weight: bold;");
            indexHeader.setPrefWidth(30);
            
            Label titleHeader = new Label("歌曲");
            titleHeader.setStyle("-fx-font-weight: bold;");
            titleHeader.setPrefWidth(200);
            
            Label artistHeader = new Label("歌手");
            artistHeader.setStyle("-fx-font-weight: bold;");
            artistHeader.setPrefWidth(150);
            
            Label durationHeader = new Label("时长");
            durationHeader.setStyle("-fx-font-weight: bold;");
            durationHeader.setPrefWidth(80);
            
            Label actionHeader = new Label("操作");
            actionHeader.setStyle("-fx-font-weight: bold;");
            actionHeader.setPrefWidth(100);
            
            headerRow.getChildren().addAll(indexHeader, titleHeader, artistHeader, durationHeader, actionHeader);
            likedSongsList.getChildren().add(headerRow);
            
            // 添加分隔线
            Separator separator = new Separator();
            separator.setStyle("-fx-opacity: 0.3;");
            likedSongsList.getChildren().add(separator);
            
            // 添加歌曲行
            for (int i = 0; i < likedSongs.size(); i++) {
                SongsResp song = likedSongs.get(i);
                HBox songRow = createSongRow(song, i);
                likedSongsList.getChildren().add(songRow);
            }
        }
        
        return likedSongsList;
    }
    
    private HBox createSongRow(SongsResp song, int index) {
        HBox songRow = new HBox(10);
        songRow.setPadding(new Insets(8, 5, 8, 5));
        songRow.setAlignment(Pos.CENTER_LEFT);
        // 设置最小宽度
        songRow.setMinWidth(580);
        // 设置首选宽度
        songRow.setPrefWidth(650);
        
        // 序号
        Label indexLabel = new Label(String.valueOf(index + 1));
        indexLabel.setPrefWidth(30);
        indexLabel.setStyle("-fx-text-fill: #666;");
        
        // 歌曲信息
        HBox songInfo = new HBox(10);
        songInfo.setAlignment(Pos.CENTER_LEFT);
        songInfo.setPrefWidth(200);
        songInfo.setMaxWidth(200);
        
        ImageView songCover = new ImageView(new Image(song.getPicture(), 32, 32, true, true));
        
        Label titleLabel = new Label(song.getTitle());
        titleLabel.setStyle("-fx-font-weight: bold;");
        titleLabel.setMaxWidth(150);
        titleLabel.setEllipsisString("...");
        titleLabel.setTextOverrun(OverrunStyle.ELLIPSIS);
        
        songInfo.getChildren().addAll(songCover, titleLabel);
        
        // 歌手
        Label artistLabel = new Label(song.getArtist());
        artistLabel.setPrefWidth(150);
        artistLabel.setMaxWidth(150);
        artistLabel.setStyle("-fx-text-fill: #666;");
        artistLabel.setEllipsisString("...");
        artistLabel.setTextOverrun(OverrunStyle.ELLIPSIS);
        
        // 时长
        Label durationLabel = new Label(formatDuration(song.getDuration()));
        durationLabel.setPrefWidth(80);
        durationLabel.setStyle("-fx-text-fill: #666;");
        
        // 操作区域
        HBox actionBox = new HBox(10);
        actionBox.setAlignment(Pos.CENTER_LEFT);
        actionBox.setPrefWidth(100);
        
        // 取消喜欢按钮
        Button unlikeButton = new Button();
        unlikeButton.setGraphic(new ImageView(new Image("static/heart-filled.png", 16, 16, true, true)));
        unlikeButton.setStyle("-fx-background-color: transparent;");
        unlikeButton.setTooltip(new Tooltip("取消喜欢"));
        
        // 添加点击事件
        unlikeButton.setOnAction(e -> {
            // 取消喜欢
            Result<Boolean> result = songsLikedController.unlike(song.getId());
            if (result.isSuccess()) {
                // 从列表中移除这一行
                Platform.runLater(() -> {
                    VBox parent = (VBox) songRow.getParent();
                    parent.getChildren().remove(songRow);
                    
                    // 如果移除后列表为空，显示空列表提示
                    if (parent.getChildren().size() <= 2) { // 表头和分隔线占2项
                        Label emptyLabel = new Label("暂无喜欢的歌曲");
                        emptyLabel.setStyle("-fx-text-fill: #999; -fx-font-style: italic;");
                        parent.getChildren().add(emptyLabel);
                    }
                });
            }
        });
        
        // 添加到歌单按钮
        Button addToPlaylistButton = new Button();
        addToPlaylistButton.setGraphic(new ImageView(new Image("static/add-to-playlist.png", 16, 16, true, true)));
        addToPlaylistButton.setStyle("-fx-background-color: transparent;");
        addToPlaylistButton.setTooltip(new Tooltip("添加到歌单"));
        
        // 添加点击事件
        addToPlaylistButton.setOnAction(e -> {
            // 调用主UI中的添加到歌单对话框
            if (mainUI != null) {
                mainUI.showAddToPlaylistDialog(song);
            } else {
                log.error("mainUI实例为空，无法调用添加到歌单对话框");
                // 显示错误提示
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("无法添加歌曲到歌单，请稍后再试");
                alert.showAndWait();
            }
        });
        
        // 将按钮添加到操作区域
        actionBox.getChildren().addAll(unlikeButton, addToPlaylistButton);
        
        songRow.getChildren().addAll(indexLabel, songInfo, artistLabel, durationLabel, actionBox);
        
        // 添加鼠标悬停效果
        songRow.setOnMouseEntered(e -> {
            songRow.setStyle("-fx-background-color: #f5f5f5; -fx-background-radius: 5px;");
        });
        
        songRow.setOnMouseExited(e -> {
            songRow.setStyle("-fx-background-color: transparent;");
        });
        
        // 添加双击播放功能
        songRow.setOnMouseClicked(e -> {
            if (e.getClickCount() == 2) {
                currentSong = song;
                player.play(song.getFilePath());
                if (songSelectedCallback != null) {
                    songSelectedCallback.onSongSelected(song);
                }
                log.info("播放歌曲: {}", song.getTitle());
            }
        });
        
        return songRow;
    }
    
    // 创建统计卡片的辅助方法
    private VBox createStatsCard(String title, String count, String iconPath) {
        VBox card = new VBox(10);
        card.setPadding(new Insets(20));
        card.setMinWidth(150);
        card.setAlignment(Pos.CENTER);
        card.setStyle("-fx-background-color: white; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 0);");
        
        // 图标
        ImageView iconView = new ImageView(new Image(iconPath));
        iconView.setFitWidth(40);
        iconView.setFitHeight(40);
        
        // 数量
        VBox countBox = new VBox(0);
        countBox.setAlignment(Pos.CENTER);
        Label countLabel = new Label(count);
        countLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold; -fx-text-fill: #1db954;");
        countBox.getChildren().add(countLabel);
        
        // 标题
        Label titleLabel = new Label(title);
        titleLabel.setStyle("-fx-font-size: 14px;");
        
        card.getChildren().addAll(iconView, countBox, titleLabel);
        
        // 添加鼠标悬停效果
        card.setOnMouseEntered(e -> {
            card.setStyle("-fx-background-color: #f8f8f8; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 8, 0, 0, 0);");
        });
        
        card.setOnMouseExited(e -> {
            card.setStyle("-fx-background-color: white; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 0);");
        });
        
        return card;
    }
    
    // 格式化时间为 mm:ss
    private String formatDuration(int seconds) {
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;
        return String.format("%02d:%02d", minutes, remainingSeconds);
    }
    
    // 回调接口，用于通知主UI更新当前歌曲
    public interface SongSelectedCallback {
        void onSongSelected(SongsResp song);
    }
    
    // 回调接口，用于通知主UI更新用户信息
    public interface UserInfoUpdatedCallback {
        void onUserInfoUpdated(UsersResp updatedUser);
    }
    
    /**
     * 显示编辑个人资料对话框
     * @param currentUser 当前用户信息
     */
    private void showEditProfileDialog(UsersResp currentUser) {
        if (currentUser == null) {
            return;
        }
        
        // 创建对话框
        Dialog<UsersReq> dialog = new Dialog<>();
        dialog.setTitle("修改个人资料");
        dialog.setHeaderText(null); // 移除默认标题，使用自定义标题
        
        // 设置对话框大小
        dialog.getDialogPane().setPrefWidth(550);
        dialog.getDialogPane().setPrefHeight(450);
        
        // 设置按钮
        ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);
        
        // 美化按钮样式
        dialog.getDialogPane().lookupButton(saveButtonType).setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-text-fill: white; " +
                "-fx-font-weight: bold; " +
                "-fx-padding: 8 20; " +
                "-fx-background-radius: 20;"
        );
        
        dialog.getDialogPane().lookupButton(ButtonType.CANCEL).setStyle(
                "-fx-background-color: #f0f0f0; " +
                "-fx-text-fill: #333333; " +
                "-fx-padding: 8 20; " +
                "-fx-background-radius: 20;"
        );
        
        // 创建主容器
        VBox mainContainer = new VBox(20);
        mainContainer.setPadding(new Insets(25));
        mainContainer.setStyle("-fx-background-color: white;");
        
        // 添加标题
        Label titleLabel = new Label("请修改您的个人资料");
        titleLabel.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #333333;");
        
        // 创建表单容器
        VBox formContainer = new VBox(15);
        formContainer.setPadding(new Insets(10, 0, 10, 0));
        
        // 用户名输入框
        VBox usernameBox = new VBox(5);
        Label usernameLabel = new Label("用户名");
        usernameLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #555555;");
        
        TextField usernameField = new TextField();
        usernameField.setText(currentUser.getUsername());
        usernameField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        usernameBox.getChildren().addAll(usernameLabel, usernameField);
        
        // 个性签名输入框
        VBox signatureBox = new VBox(5);
        Label signatureLabel = new Label("个性签名");
        signatureLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #555555;");
        
        TextArea signatureArea = new TextArea();
        signatureArea.setWrapText(true);
        signatureArea.setPrefRowCount(3);
        if (currentUser.getSignature() != null) {
            signatureArea.setText(currentUser.getSignature());
        }
        signatureArea.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        signatureBox.getChildren().addAll(signatureLabel, signatureArea);
        
        // 头像选择器
        VBox avatarBox = new VBox(10);
        Label avatarTitleLabel = new Label("头像");
        avatarTitleLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #555555;");
        
        HBox avatarContent = new HBox(15);
        avatarContent.setAlignment(Pos.CENTER_LEFT);
        
        // 显示当前头像
        StackPane avatarContainer = new StackPane();
        avatarContainer.setStyle(
                "-fx-background-color: white; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 0);"
        );
        
        ImageView currentAvatar = new ImageView();
        currentAvatar.setFitWidth(80);
        currentAvatar.setFitHeight(80);
        
        // 圆形裁剪
        Circle clip = new Circle(40, 40, 40);
        currentAvatar.setClip(clip);
        
        // 设置头像图片
        String avatarPath = "static/default-avatar.png";
        if (currentUser.getAvatar() != null && !currentUser.getAvatar().isEmpty()) {
            avatarPath = currentUser.getAvatar();
        }
        currentAvatar.setImage(new Image(avatarPath));
        avatarContainer.getChildren().add(currentAvatar);
        
        // 头像相关操作区域
        VBox avatarActions = new VBox(10);
        avatarActions.setAlignment(Pos.CENTER_LEFT);
        
        // 选择头像按钮
        Button selectAvatarButton = new Button("选择头像");
        selectAvatarButton.setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-text-fill: white; " +
                "-fx-font-weight: bold; " +
                "-fx-padding: 8 15; " +
                "-fx-background-radius: 20;"
        );
        
        // 头像文件路径
        Label avatarPathLabel = new Label(avatarPath);
        avatarPathLabel.setMaxWidth(250);
        avatarPathLabel.setEllipsisString("...");
        avatarPathLabel.setTextOverrun(OverrunStyle.ELLIPSIS);
        avatarPathLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #888888;");
        
        avatarActions.getChildren().addAll(selectAvatarButton, avatarPathLabel);
        avatarContent.getChildren().addAll(avatarContainer, avatarActions);
        avatarBox.getChildren().addAll(avatarTitleLabel, avatarContent);
        
        // 用于存储选择的头像文件
        final java.io.File[] selectedAvatarFile = new java.io.File[1];
        
        // 将所有表单元素添加到表单容器
        formContainer.getChildren().addAll(usernameBox, signatureBox, avatarBox);
        
        // 将标题和表单添加到主容器
        mainContainer.getChildren().addAll(titleLabel, formContainer);
        
        // 设置对话框内容
        dialog.getDialogPane().setContent(mainContainer);
        
        // 设置选择头像按钮事件
        selectAvatarButton.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择头像图片");
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg", "*.gif")
            );
            
            // 显示文件选择器对话框
            javafx.stage.Window window = dialog.getDialogPane().getScene().getWindow();
            java.io.File selectedFile = fileChooser.showOpenDialog(window);
            
            if (selectedFile != null) {
                try {
                    // 保存选择的文件引用
                    selectedAvatarFile[0] = selectedFile;
                    
                    // 获取文件路径
                    String selectedPath = selectedFile.toURI().toString();
                    
                    // 更新头像预览
                    currentAvatar.setImage(new Image(selectedPath));
                    avatarPathLabel.setText(selectedFile.getName());
                } catch (Exception e) {
                    log.error("加载头像失败", e);
                    // 显示错误提示
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("错误");
                    alert.setHeaderText(null);
                    alert.setContentText("加载头像失败，请重试");
                    alert.showAndWait();
                }
            }
        });
        
        // 请求焦点到用户名字段
        Platform.runLater(usernameField::requestFocus);
        
        // 转换结果
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == saveButtonType) {
                UsersReq usersReq = new UsersReq();
                usersReq.setUsername(usernameField.getText().trim());
                usersReq.setSignature(signatureArea.getText().trim());
                
                // 设置头像文件
                if (selectedAvatarFile[0] != null) {
                    usersReq.setAvatar(selectedAvatarFile[0]);
                }
                
                return usersReq;
            }
            return null;
        });
        
        // 显示对话框并处理结果
        dialog.showAndWait().ifPresent(usersReq -> {
            // 调用后端接口更新用户信息
            Result<Boolean> result = usersController.updateUserInfo(usersReq);
            if (result.isSuccess()) {
                // 刷新个人中心页面
                Platform.runLater(() -> {
                    // 获取最新的用户信息
                    Result<UsersResp> userInfoResult = usersController.getCurrentUserInfo();
                    if (userInfoResult.isSuccess()) {
                        UsersResp updatedUser = userInfoResult.getData();
                        
                        try {
                            // 创建新的用户信息卡片
                            VBox userInfoCard = createUserInfoCard(updatedUser);
                            
                            // 使用保存的contentBox引用直接更新用户信息卡片
                            if (contentBox != null && contentBox.getChildren().size() > 1) {
                                // 用户信息卡片在索引1的位置
                                contentBox.getChildren().set(1, userInfoCard);
                                
                                // 更新统计信息卡片
                                HBox statsCards = createStatsCards();
                                if (contentBox.getChildren().size() > 2) {
                                    contentBox.getChildren().set(2, statsCards);
                                }
                                
                                // 通知主界面更新用户信息
                                if (userInfoUpdatedCallback != null) {
                                    userInfoUpdatedCallback.onUserInfoUpdated(updatedUser);
                                }
                                
                                // 显示成功提示
                                Alert successAlert = new Alert(Alert.AlertType.INFORMATION);
                                successAlert.setTitle("成功");
                                successAlert.setHeaderText(null);
                                successAlert.setContentText("个人资料修改成功");
                                successAlert.showAndWait();
                            } else {
                                log.error("内容容器为空或结构不正确");
                                // 显示错误提示
                                Alert errorAlert = new Alert(Alert.AlertType.ERROR);
                                errorAlert.setTitle("错误");
                                errorAlert.setHeaderText(null);
                                errorAlert.setContentText("更新失败，请重新打开个人中心");
                                errorAlert.showAndWait();
                            }
                        } catch (Exception ex) {
                            log.error("处理个人资料更新失败", ex);
                            // 显示错误提示
                            Alert errorAlert = new Alert(Alert.AlertType.ERROR);
                            errorAlert.setTitle("错误");
                            errorAlert.setHeaderText(null);
                            errorAlert.setContentText("更新失败，请重新打开个人中心");
                            errorAlert.showAndWait();
                        }
                    }
                });
            } else {
                // 更新失败提示
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("修改失败：" + result.getMessage());
                alert.showAndWait();
            }
        });
    }
    
    /**
     * 显示绑定手机对话框
     * @param currentUser 当前用户信息
     */
    private void showBindPhoneDialog(UsersResp currentUser) {
        if (currentUser == null) {
            return;
        }
        
        // 创建对话框
        Dialog<UsersReq> dialog = new Dialog<>();
        dialog.setTitle("绑定手机");
        dialog.setHeaderText(null);
        
        // 设置对话框大小
        dialog.getDialogPane().setPrefWidth(450);
        dialog.getDialogPane().setPrefHeight(350);
        
        // 设置按钮
        ButtonType bindButtonType = new ButtonType("绑定", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(bindButtonType, ButtonType.CANCEL);
        
        // 美化按钮样式
        dialog.getDialogPane().lookupButton(bindButtonType).setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-text-fill: white; " +
                "-fx-font-weight: bold; " +
                "-fx-padding: 8 20; " +
                "-fx-background-radius: 20;"
        );
        
        dialog.getDialogPane().lookupButton(ButtonType.CANCEL).setStyle(
                "-fx-background-color: #f0f0f0; " +
                "-fx-text-fill: #333333; " +
                "-fx-padding: 8 20; " +
                "-fx-background-radius: 20;"
        );
        
        // 创建主容器
        VBox mainContainer = new VBox(20);
        mainContainer.setPadding(new Insets(25));
        mainContainer.setStyle("-fx-background-color: white;");
        
        // 添加标题
        Label titleLabel = new Label("绑定手机号");
        titleLabel.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #333333;");
        
        // 创建表单容器
        VBox formContainer = new VBox(15);
        formContainer.setPadding(new Insets(10, 0, 10, 0));
        
        // 显示当前手机号（如果有）
        VBox currentPhoneBox = new VBox(5);
        Label currentPhoneLabel = new Label("当前手机号");
        currentPhoneLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #555555;");
        
        Label currentPhoneValue = new Label(currentUser.getPhone() != null ? currentUser.getPhone() : "未绑定");
        currentPhoneValue.setStyle("-fx-text-fill: " + (currentUser.getPhone() != null ? "#1db954" : "#888888") + ";");
        
        currentPhoneBox.getChildren().addAll(currentPhoneLabel, currentPhoneValue);
        
        // 手机号输入框
        VBox phoneBox = new VBox(5);
        Label phoneLabel = new Label("新手机号");
        phoneLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #555555;");
        
        HBox phoneInputBox = new HBox(10);
        phoneInputBox.setAlignment(Pos.CENTER_LEFT);
        
        TextField phoneField = new TextField();
        phoneField.setPromptText("请输入11位手机号");
        phoneField.setPrefWidth(250);
        phoneField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        // 发送验证码按钮
        Button sendCodeButton = new Button("发送验证码");
        sendCodeButton.setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-text-fill: white; " +
                "-fx-font-weight: bold; " +
                "-fx-padding: 8 15; " +
                "-fx-background-radius: 5;"
        );
        
        phoneInputBox.getChildren().addAll(phoneField, sendCodeButton);
        phoneBox.getChildren().addAll(phoneLabel, phoneInputBox);
        
        // 验证码输入框
        VBox codeBox = new VBox(5);
        Label codeLabel = new Label("验证码");
        codeLabel.setStyle("-fx-font-weight: bold; -fx-text-fill: #555555;");
        
        TextField codeField = new TextField();
        codeField.setPromptText("请输入收到的验证码");
        codeField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        codeBox.getChildren().addAll(codeLabel, codeField);
        
        // 添加提示信息
        Label tipLabel = new Label("绑定手机后，可用于账号登录和找回密码");
        tipLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #888888; -fx-font-style: italic;");
        
        // 将所有表单元素添加到表单容器
        formContainer.getChildren().addAll(currentPhoneBox, phoneBox, codeBox, tipLabel);
        
        // 将标题和表单添加到主容器
        mainContainer.getChildren().addAll(titleLabel, formContainer);
        
        // 设置对话框内容
        dialog.getDialogPane().setContent(mainContainer);
        
        // 发送验证码按钮事件
        final int[] countdown = {60}; // 倒计时秒数
        final Timeline[] countdownTimeline = {null};
        final String[] currentCode = {null}; // 存储当前验证码
        
        sendCodeButton.setOnAction(event -> {
            String phone = phoneField.getText().trim();
            
            // 验证手机号格式
            if (!isValidPhoneNumber(phone)) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("请输入正确的手机号码");
                alert.showAndWait();
                return;
            }
            
            // 发送验证码请求
            try {
                // 调用后端接口发送验证码
                Result<Boolean> result = usersController.sendPhoneCode(phone);
                
                if (!result.isSuccess()) {
                    // 发送失败
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("错误");
                    alert.setHeaderText(null);
                    alert.setContentText("发送验证码失败：" + result.getMessage());
                    alert.showAndWait();
                    return;
                }
                
                // 获取验证码（实际项目中不应该这样做，这里是为了演示）
                String code = usersController.getLastSentCode(phone);
                currentCode[0] = code;
                
                // 禁用发送按钮并开始倒计时
                sendCodeButton.setDisable(true);
                
                // 创建倒计时
                if (countdownTimeline[0] != null) {
                    countdownTimeline[0].stop();
                }
                
                countdown[0] = 60;
                sendCodeButton.setText(code); // 直接在按钮上显示验证码
                
                countdownTimeline[0] = new Timeline(
                    new KeyFrame(Duration.seconds(1), e -> {
                        countdown[0]--;
                        if (countdown[0] > 0) {
                            // 保持显示验证码
                            sendCodeButton.setText(code);
                        } else {
                            sendCodeButton.setText("发送验证码");
                            sendCodeButton.setDisable(false);
                            countdownTimeline[0].stop();
                        }
                    })
                );
                countdownTimeline[0].setCycleCount(countdown[0]);
                countdownTimeline[0].play();
                
                // 自动填充验证码到输入框
                codeField.setText(code);
                
            } catch (Exception ex) {
                log.error("发送验证码失败", ex);
                
                // 显示错误提示
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText(null);
                alert.setContentText("发送验证码失败，请稍后重试");
                alert.showAndWait();
            }
        });
        
        // 请求焦点到手机号字段
        Platform.runLater(phoneField::requestFocus);
        
        // 转换结果
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == bindButtonType) {
                String phone = phoneField.getText().trim();
                String code = codeField.getText().trim();
                
                // 验证输入
                if (phone.isEmpty() || code.isEmpty()) {
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("错误");
                    alert.setHeaderText(null);
                    alert.setContentText("手机号和验证码不能为空");
                    alert.showAndWait();
                    return null;
                }
                
                // 创建请求对象
                UsersReq usersReq = new UsersReq(phone, "", code);
                return usersReq;
            }
            return null;
        });
        
        // 显示对话框并处理结果
        dialog.showAndWait().ifPresent(usersReq -> {
            if (usersReq != null) {
                // 调用后端接口绑定手机号
                try {
                    // 实际调用后端接口绑定手机号
                    Result<Boolean> result = usersController.bindPhone(usersReq);
                    
                    if (result.isSuccess()) {
                        // 刷新个人中心页面
                        Platform.runLater(() -> {
                            // 获取最新的用户信息
                            Result<UsersResp> userInfoResult = usersController.getCurrentUserInfo();
                            if (userInfoResult.isSuccess()) {
                                UsersResp updatedUser = userInfoResult.getData();
                                
                                try {
                                    // 创建新的用户信息卡片
                                    VBox userInfoCard = createUserInfoCard(updatedUser);
                                    
                                    // 使用保存的contentBox引用直接更新用户信息卡片
                                    if (contentBox != null && contentBox.getChildren().size() > 1) {
                                        // 用户信息卡片在索引1的位置
                                        contentBox.getChildren().set(1, userInfoCard);
                                        
                                        // 通知主界面更新用户信息
                                        if (userInfoUpdatedCallback != null) {
                                            userInfoUpdatedCallback.onUserInfoUpdated(updatedUser);
                                        }
                                        
                                        // 显示成功提示
                                        Alert successAlert = new Alert(Alert.AlertType.INFORMATION);
                                        successAlert.setTitle("成功");
                                        successAlert.setHeaderText(null);
                                        successAlert.setContentText("手机号绑定成功");
                                        successAlert.showAndWait();
                                    }
                                } catch (Exception ex) {
                                    log.error("处理手机绑定后更新失败", ex);
                                    // 显示错误提示
                                    Alert errorAlert = new Alert(Alert.AlertType.ERROR);
                                    errorAlert.setTitle("错误");
                                    errorAlert.setHeaderText(null);
                                    errorAlert.setContentText("更新失败，请重新打开个人中心");
                                    errorAlert.showAndWait();
                                }
                            }
                        });
                    } else {
                        // 显示错误提示
                        Alert alert = new Alert(Alert.AlertType.ERROR);
                        alert.setTitle("错误");
                        alert.setHeaderText(null);
                        alert.setContentText("绑定失败: " + result.getMessage());
                        alert.showAndWait();
                    }
                } catch (Exception ex) {
                    log.error("绑定手机号失败", ex);
                    
                    // 显示错误提示
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("错误");
                    alert.setHeaderText(null);
                    alert.setContentText("绑定手机号失败，请稍后重试");
                    alert.showAndWait();
                }
            }
        });
        
        // 清理倒计时
        if (countdownTimeline[0] != null) {
            countdownTimeline[0].stop();
        }
    }
    
    /**
     * 验证手机号格式
     * @param phone 手机号
     * @return 是否是有效的手机号
     */
    private boolean isValidPhoneNumber(String phone) {
        if (phone == null || phone.isEmpty()) {
            return false;
        }
        // 简单验证手机号是否为11位数字
        return phone.matches("^1\\d{10}$");
    }
    
    /**
     * 创建上传音乐区域
     */
    private VBox createUploadMusicBox() {
        VBox uploadMusicBox = new VBox(15);
        uploadMusicBox.setPadding(new Insets(20));
        uploadMusicBox.setStyle("-fx-background-color: white; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 10, 0, 0, 0);");
        
        // 标题
        Label titleLabel = new Label("上传音乐");
        titleLabel.setStyle("-fx-font-size: 18px; -fx-font-weight: bold;");
        
        // 上传按钮
        Button uploadButton = new Button("上传我的音乐");
        uploadButton.setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-text-fill: white; " +
                "-fx-font-weight: bold; " +
                "-fx-padding: 10 20; " +
                "-fx-background-radius: 20;"
        );
        
        // 添加按钮点击事件
        uploadButton.setOnAction(e -> {
            showUploadMusicDialog();
        });
        
        // 提示信息
        Label tipLabel = new Label("您可以上传自己的音乐，分享给其他用户");
        tipLabel.setStyle("-fx-font-size: 14px; -fx-text-fill: #666666;");
        
        // 将组件添加到容器
        uploadMusicBox.getChildren().addAll(titleLabel, uploadButton, tipLabel);
        uploadMusicBox.setAlignment(Pos.CENTER_LEFT);
        
        return uploadMusicBox;
    }
    
    /**
     * 显示上传音乐对话框
     */
    private void showUploadMusicDialog() {
        // 创建对话框
        Dialog<SongsReq> dialog = new Dialog<>();
        dialog.setTitle("上传音乐");
        dialog.setHeaderText(null);
        
        // 设置对话框大小
        dialog.getDialogPane().setPrefWidth(550);
        dialog.getDialogPane().setPrefHeight(600);
        
        // 设置按钮
        ButtonType uploadButtonType = new ButtonType("上传", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(uploadButtonType, ButtonType.CANCEL);
        
        // 美化按钮样式
        dialog.getDialogPane().lookupButton(uploadButtonType).setStyle(
                "-fx-background-color: #1db954; " +
                "-fx-text-fill: white; " +
                "-fx-font-weight: bold; " +
                "-fx-padding: 8 20; " +
                "-fx-background-radius: 20;"
        );
        
        dialog.getDialogPane().lookupButton(ButtonType.CANCEL).setStyle(
                "-fx-background-color: #f0f0f0; " +
                "-fx-text-fill: #333333; " +
                "-fx-padding: 8 20; " +
                "-fx-background-radius: 20;"
        );
        
        // 创建主容器
        VBox mainContainer = new VBox(20);
        mainContainer.setPadding(new Insets(25));
        mainContainer.setStyle("-fx-background-color: white;");
        
        // 添加标题
        Label titleLabel = new Label("请填写音乐信息");
        titleLabel.setStyle("-fx-font-size: 20px; -fx-font-weight: bold; -fx-text-fill: #333333;");
        
        // 创建表单容器
        GridPane formGrid = new GridPane();
        formGrid.setHgap(15);
        formGrid.setVgap(15);
        formGrid.setPadding(new Insets(10, 0, 10, 0));
        
        // 设置列宽约束
        ColumnConstraints labelColumn = new ColumnConstraints();
        labelColumn.setMinWidth(80);
        labelColumn.setPrefWidth(100);
        labelColumn.setMaxWidth(120);
        
        ColumnConstraints inputColumn = new ColumnConstraints();
        inputColumn.setMinWidth(300);
        inputColumn.setPrefWidth(350);
        inputColumn.setMaxWidth(400);
        inputColumn.setHgrow(Priority.ALWAYS);
        
        formGrid.getColumnConstraints().addAll(labelColumn, inputColumn);
        
        // 歌曲名称
        Label songTitleLabel = new Label("歌曲名称:");
        songTitleLabel.setStyle("-fx-font-weight: bold;");
        TextField songTitleField = new TextField();
        songTitleField.setPromptText("请输入歌曲名称");
        songTitleField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        // 歌手名称
        Label artistLabel = new Label("歌手名称:");
        artistLabel.setStyle("-fx-font-weight: bold;");
        TextField artistField = new TextField();
        artistField.setPromptText("请输入歌手名称");
        artistField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        // 专辑名称（可选）
        Label albumLabel = new Label("专辑名称:");
        albumLabel.setStyle("-fx-font-weight: bold;");
        TextField albumField = new TextField();
        albumField.setPromptText("请输入专辑名称（可选）");
        albumField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        // 音乐文件
        Label musicFileLabel = new Label("音乐文件:");
        musicFileLabel.setStyle("-fx-font-weight: bold;");
        HBox musicFileBox = new HBox(10);
        TextField musicFileField = new TextField();
        musicFileField.setPromptText("请选择音乐文件");
        musicFileField.setEditable(false);
        musicFileField.setPrefWidth(280);
        musicFileField.setMaxWidth(280);
        musicFileField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        Button selectMusicButton = new Button("选择文件");
        selectMusicButton.setStyle(
                "-fx-background-color: #f0f0f0; " +
                "-fx-text-fill: #333333; " +
                "-fx-padding: 8 15; " +
                "-fx-background-radius: 5;"
        );
        musicFileBox.getChildren().addAll(musicFileField, selectMusicButton);
        
        // 封面图片
        Label coverImageLabel = new Label("封面图片:");
        coverImageLabel.setStyle("-fx-font-weight: bold;");
        HBox coverImageBox = new HBox(10);
        TextField coverImageField = new TextField();
        coverImageField.setPromptText("请选择封面图片");
        coverImageField.setEditable(false);
        coverImageField.setPrefWidth(280);
        coverImageField.setMaxWidth(280);
        coverImageField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        Button selectCoverButton = new Button("选择图片");
        selectCoverButton.setStyle(
                "-fx-background-color: #f0f0f0; " +
                "-fx-text-fill: #333333; " +
                "-fx-padding: 8 15; " +
                "-fx-background-radius: 5;"
        );
        coverImageBox.getChildren().addAll(coverImageField, selectCoverButton);
        
        // 歌词文件（可选）
        Label lyricsLabel = new Label("歌词文件:");
        lyricsLabel.setStyle("-fx-font-weight: bold;");
        HBox lyricsBox = new HBox(10);
        TextField lyricsField = new TextField();
        lyricsField.setPromptText("请选择歌词文件（可选）");
        lyricsField.setEditable(false);
        lyricsField.setPrefWidth(280);
        lyricsField.setMaxWidth(280);
        lyricsField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        Button selectLyricsButton = new Button("选择文件");
        selectLyricsButton.setStyle(
                "-fx-background-color: #f0f0f0; " +
                "-fx-text-fill: #333333; " +
                "-fx-padding: 8 15; " +
                "-fx-background-radius: 5;"
        );
        lyricsBox.getChildren().addAll(lyricsField, selectLyricsButton);
        
        // 关键歌词（可选）
        Label keyLyricsLabel = new Label("关键歌词:");
        keyLyricsLabel.setStyle("-fx-font-weight: bold;");
        TextArea keyLyricsField = new TextArea();
        keyLyricsField.setPromptText("请输入关键歌词（可选）");
        keyLyricsField.setWrapText(true);
        keyLyricsField.setPrefRowCount(3);
        keyLyricsField.setMaxWidth(350);
        keyLyricsField.setPrefWidth(350);
        keyLyricsField.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-border-color: #e0e0e0; " +
                "-fx-border-radius: 5; " +
                "-fx-background-radius: 5; " +
                "-fx-padding: 8;"
        );
        
        // 添加表单元素到网格
        formGrid.add(songTitleLabel, 0, 0);
        formGrid.add(songTitleField, 1, 0);
        formGrid.add(artistLabel, 0, 1);
        formGrid.add(artistField, 1, 1);
        formGrid.add(albumLabel, 0, 2);
        formGrid.add(albumField, 1, 2);
        formGrid.add(musicFileLabel, 0, 3);
        formGrid.add(musicFileBox, 1, 3);
        formGrid.add(coverImageLabel, 0, 4);
        formGrid.add(coverImageBox, 1, 4);
        formGrid.add(lyricsLabel, 0, 5);
        formGrid.add(lyricsBox, 1, 5);
        formGrid.add(keyLyricsLabel, 0, 6);
        formGrid.add(keyLyricsField, 1, 6);
        
        // 提示信息
        Label tipLabel = new Label("支持的音乐格式: MP3, WAV, FLAC");
        tipLabel.setStyle("-fx-font-size: 12px; -fx-text-fill: #888888; -fx-font-style: italic;");
        
        // 将标题、表单和提示添加到主容器
        mainContainer.getChildren().addAll(titleLabel, formGrid, tipLabel);
        
        // 设置对话框内容
        dialog.getDialogPane().setContent(mainContainer);
        
        // 用于存储选择的文件
        final java.io.File[] selectedMusicFile = new java.io.File[1];
        final java.io.File[] selectedCoverFile = new java.io.File[1];
        final java.io.File[] selectedLyricsFile = new java.io.File[1];
        
        // 选择音乐文件按钮事件
        selectMusicButton.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择音乐文件");
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("音乐文件", "*.mp3", "*.wav", "*.flac")
            );
            
            // 显示文件选择器对话框
            javafx.stage.Window window = dialog.getDialogPane().getScene().getWindow();
            java.io.File selectedFile = fileChooser.showOpenDialog(window);
            
            if (selectedFile != null) {
                selectedMusicFile[0] = selectedFile;
                musicFileField.setText(selectedFile.getName());
            }
        });
        
        // 选择封面图片按钮事件
        selectCoverButton.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择封面图片");
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg")
            );
            
            // 显示文件选择器对话框
            javafx.stage.Window window = dialog.getDialogPane().getScene().getWindow();
            java.io.File selectedFile = fileChooser.showOpenDialog(window);
            
            if (selectedFile != null) {
                selectedCoverFile[0] = selectedFile;
                coverImageField.setText(selectedFile.getName());
            }
        });
        
        // 选择歌词文件按钮事件
        selectLyricsButton.setOnAction(event -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择歌词文件");
            fileChooser.getExtensionFilters().addAll(
                    new FileChooser.ExtensionFilter("歌词文件", "*.lrc")
            );
            
            // 显示文件选择器对话框
            javafx.stage.Window window = dialog.getDialogPane().getScene().getWindow();
            java.io.File selectedFile = fileChooser.showOpenDialog(window);
            
            if (selectedFile != null) {
                selectedLyricsFile[0] = selectedFile;
                lyricsField.setText(selectedFile.getName());
            }
        });
        
        // 请求焦点到歌曲名称字段
        Platform.runLater(songTitleField::requestFocus);
        
        // 转换结果
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == uploadButtonType) {
                // 验证必填字段
                if (songTitleField.getText().trim().isEmpty() || 
                    artistField.getText().trim().isEmpty() || 
                    selectedMusicFile[0] == null || 
                    selectedCoverFile[0] == null) {
                    
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setTitle("错误");
                    alert.setHeaderText(null);
                    alert.setContentText("请填写歌曲名称、歌手名称并选择音乐文件和封面图片");
                    alert.showAndWait();
                    return null;
                }
                
                // 创建请求对象
                SongsReq songsReq = new SongsReq();
                songsReq.setTitle(songTitleField.getText().trim());
                songsReq.setArtist(artistField.getText().trim());
                
                // 专辑名称是可选的
                String album = albumField.getText().trim();
                if (!album.isEmpty()) {
                    songsReq.setAlbum(album);
                }
                
                songsReq.setSongFile(selectedMusicFile[0]);
                songsReq.setPicture(selectedCoverFile[0]);
                
                // 计算音频文件时长
                int duration = AudioUtils.getAudioDuration(selectedMusicFile[0]);
                songsReq.setDuration(duration);
                
                if (selectedLyricsFile[0] != null) {
                    songsReq.setLrc(selectedLyricsFile[0]);
                }
                
                // 设置关键歌词
                if (!keyLyricsField.getText().trim().isEmpty()) {
                    songsReq.setKeyLrc(keyLyricsField.getText().trim());
                }
                
                return songsReq;
            }
            return null;
        });
        
        // 显示对话框并处理结果
        dialog.showAndWait().ifPresent(songsReq -> {
            if (songsReq != null) {
                // 显示上传中提示
                Alert uploadingAlert = new Alert(Alert.AlertType.INFORMATION);
                uploadingAlert.setTitle("上传中");
                uploadingAlert.setHeaderText(null);
                uploadingAlert.setContentText("正在上传音乐，请稍候...");
                
                // 不阻塞UI线程，使用异步处理
                Platform.runLater(() -> {
                    try {
                        // 调用后端接口上传音乐
                        Result<Boolean> result = songsController.uploadSong(songsReq);
                        
                        // 关闭上传中提示
                        uploadingAlert.close();
                        
                        if (result.isSuccess()) {
                            // 上传成功提示
                            Alert successAlert = new Alert(Alert.AlertType.INFORMATION);
                            successAlert.setTitle("成功");
                            successAlert.setHeaderText(null);
                            successAlert.setContentText("音乐上传成功！");
                            successAlert.showAndWait();
                        } else {
                            // 上传失败提示
                            Alert errorAlert = new Alert(Alert.AlertType.ERROR);
                            errorAlert.setTitle("错误");
                            errorAlert.setHeaderText(null);
                            errorAlert.setContentText("上传失败：" + result.getMessage());
                            errorAlert.showAndWait();
                        }
                    } catch (Exception ex) {
                        log.error("上传音乐失败", ex);
                        
                        // 关闭上传中提示
                        uploadingAlert.close();
                        
                        // 显示错误提示
                        Alert errorAlert = new Alert(Alert.AlertType.ERROR);
                        errorAlert.setTitle("错误");
                        errorAlert.setHeaderText(null);
                        errorAlert.setContentText("上传失败，请稍后重试");
                        errorAlert.showAndWait();
                    }
                });
                
                // 显示上传中提示
                uploadingAlert.show();
            }
        });
    }
    
    /**
     * 创建最近播放列表
     */
    private VBox createRecentPlaysList() {
        VBox recentPlaysList = new VBox(5);
        recentPlaysList.setPadding(new Insets(10));
        recentPlaysList.setStyle("-fx-background-color: white; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 0);");
        recentPlaysList.setMinWidth(600); // 设置最小宽度
        recentPlaysList.setPrefWidth(700); // 设置首选宽度
        recentPlaysList.setMaxWidth(800); // 设置最大宽度
        
        // TODO: 从后端获取最近播放列表
        // 这里暂时显示一个提示信息
        Label infoLabel = new Label("最近播放功能正在开发中...");
        infoLabel.setStyle("-fx-text-fill: #999; -fx-font-style: italic;");
        recentPlaysList.getChildren().add(infoLabel);
        
        return recentPlaysList;
    }
    
    /**
     * 创建歌单列表
     */
    private VBox createPlaylistsList() {
        VBox playlistsContainer = new VBox(15);
        playlistsContainer.setPadding(new Insets(10));
        playlistsContainer.setStyle("-fx-background-color: white; -fx-background-radius: 10px; -fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 0);");
        playlistsContainer.setMinWidth(600); // 设置最小宽度
        playlistsContainer.setPrefWidth(700); // 设置首选宽度
        playlistsContainer.setMaxWidth(800); // 设置最大宽度
        
        // 从后端获取歌单列表
        Result<List<PlaylistResp>> playlistResult = SpringContextUtil.getBean(PlaylistController.class).queryByUserId();
        List<PlaylistResp> playlists = new ArrayList<>();
        
        if (playlistResult.isSuccess() && playlistResult.getData() != null) {
            playlists = playlistResult.getData();
        }
        
        if (playlists.isEmpty()) {
            // 显示空歌单提示
            Label emptyLabel = new Label("暂无创建的歌单");
            emptyLabel.setStyle("-fx-text-fill: #999; -fx-font-style: italic;");
            playlistsContainer.getChildren().add(emptyLabel);
            
            // 添加创建歌单按钮
            Button createPlaylistButton = new Button("创建歌单");
            createPlaylistButton.setStyle(
                    "-fx-background-color: #1db954; " +
                    "-fx-text-fill: white; " +
                    "-fx-font-weight: bold; " +
                    "-fx-padding: 10 20; " +
                    "-fx-background-radius: 20;"
            );
            
            // 添加按钮点击事件
            createPlaylistButton.setOnAction(e -> {
                // TODO: 实现创建歌单功能
                log.info("点击了创建歌单按钮");
            });
            
            VBox.setMargin(createPlaylistButton, new Insets(15, 0, 0, 0));
            playlistsContainer.getChildren().add(createPlaylistButton);
        } else {
            // 添加创建歌单按钮
            Button createPlaylistButton = new Button("+ 创建歌单");
            createPlaylistButton.setStyle(
                    "-fx-background-color: #1db954; " +
                    "-fx-text-fill: white; " +
                    "-fx-font-weight: bold; " +
                    "-fx-padding: 8 15; " +
                    "-fx-background-radius: 20;"
            );
            
            // 添加按钮点击事件
            createPlaylistButton.setOnAction(e -> {
                // TODO: 实现创建歌单功能
                log.info("点击了创建歌单按钮");
            });
            
            HBox buttonBox = new HBox(createPlaylistButton);
            buttonBox.setAlignment(Pos.CENTER_RIGHT);
            playlistsContainer.getChildren().add(buttonBox);
            
            // 创建歌单网格
            GridPane playlistsGrid = new GridPane();
            playlistsGrid.setHgap(20);
            playlistsGrid.setVgap(20);
            playlistsGrid.setPadding(new Insets(15, 0, 0, 0));
            
            // 添加歌单卡片
            int column = 0;
            int row = 0;
            int maxColumns = 3; // 每行最多显示3个歌单
            
            for (PlaylistResp playlist : playlists) {
                VBox playlistCard = createPlaylistCard(playlist);
                playlistsGrid.add(playlistCard, column, row);
                
                // 更新列和行
                column++;
                if (column >= maxColumns) {
                    column = 0;
                    row++;
                }
            }
            
            playlistsContainer.getChildren().add(playlistsGrid);
        }
        
        return playlistsContainer;
    }
    
    /**
     * 创建歌单卡片
     */
    private VBox createPlaylistCard(PlaylistResp playlist) {
        VBox card = new VBox(8);
        card.setPadding(new Insets(10));
        card.setMinWidth(200);
        card.setMaxWidth(200);
        card.setStyle(
                "-fx-background-color: #f8f8f8; " +
                "-fx-background-radius: 10px; " +
                "-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 0);"
        );
        card.setCursor(javafx.scene.Cursor.HAND);
        
        // 歌单封面
        ImageView coverView = new ImageView();
        coverView.setFitWidth(180);
        coverView.setFitHeight(180);
        
        // 设置封面图片
        if (playlist.getCoverUrl() != null && !playlist.getCoverUrl().isEmpty()) {
            coverView.setImage(new Image(playlist.getCoverUrl()));
        } else {
            coverView.setImage(new Image("static/default-cover.png"));
        }
        
        // 歌单名称
        Label nameLabel = new Label(playlist.getName());
        nameLabel.setStyle("-fx-font-weight: bold; -fx-font-size: 14px;");
        nameLabel.setWrapText(true);
        
        // 歌曲数量
        int songsCount = playlist.getSongsRespList() != null ? playlist.getSongsRespList().size() : 0;
        Label countLabel = new Label(songsCount + " 首歌曲");
        countLabel.setStyle("-fx-text-fill: #666; -fx-font-size: 12px;");
        
        // 创建日期
        String createDate = "";
        if (playlist.getCreateTime() != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            createDate = dateFormat.format(playlist.getCreateTime());
        }
        Label dateLabel = new Label("创建于 " + createDate);
        dateLabel.setStyle("-fx-text-fill: #888; -fx-font-size: 11px;");
        
        card.getChildren().addAll(coverView, nameLabel, countLabel, dateLabel);
        
        // 添加鼠标悬停效果
        card.setOnMouseEntered(e -> {
            card.setStyle(
                    "-fx-background-color: #f0f0f0; " +
                    "-fx-background-radius: 10px; " +
                    "-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 8, 0, 0, 0);"
            );
        });
        
        card.setOnMouseExited(e -> {
            card.setStyle(
                    "-fx-background-color: #f8f8f8; " +
                    "-fx-background-radius: 10px; " +
                    "-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.1), 5, 0, 0, 0);"
            );
        });
        
        // 添加点击事件
        card.setOnMouseClicked(e -> {
            log.info("点击了歌单: {}", playlist.getName());
            
            // 获取完整的歌单信息
            new Thread(() -> {
                try {
                    // 查询完整的歌单信息
                    Result<PlaylistResp> playlistResult = SpringContextUtil.getBean(PlaylistController.class).queryById(playlist.getId());
                    
                    if (playlistResult.isSuccess() && playlistResult.getData() != null) {
                        // 获取完整的歌单信息
                        PlaylistResp completePlaylist = playlistResult.getData();
                        
                        // 在JavaFX线程中更新UI
                        Platform.runLater(() -> {
                            // 打开歌单详情页面
                            MainMusicPlayerUi mainUI = SpringContextUtil.getBean(MainMusicPlayerUi.class);
                            mainUI.showPlaylistPage();
                            mainUI.showSelectedPlaylist(completePlaylist);
                        });
                    } else {
                        log.error("获取歌单详情失败: {}", playlistResult.getMessage());
                    }
                } catch (Exception ex) {
                    log.error("查询歌单信息异常", ex);
                }
            }).start();
        });
        
        return card;
    }
} 